import { defineStore } from "pinia";
import { isEmpty, cloneDeep, clone } from 'lodash';
import { ref } from "vue";

import { getUserInfo, apiLogout } from "@/api/user";
import { getCountOrder } from "@/api/order";

import useCarStore from "@/store/car.ts"
import useAppStore from "@/store/app.ts"
const carStore = useCarStore()
const appStore = useAppStore()

// 默认用户信息
const defaultUserInfo = {
	avatar: '', // 头像
	nickname: '', // 昵称
	gender: 0, // 性别
	phone: '', // 手机号
	verification: {}, // 认证字段
	openId: ''
};

// 默认订单信息
const defaultOrderInfo = {
	order_num: {
		aftersale: 0,
		nocomment: 0,
		noget: 0,
		nosend: 0,
		unpaid: 0,
	},
};


const useUserStore = defineStore("userStore", () => {
	const token = ref("")
	const isLogin = ref(uni.getStorageSync('token'))
	const auth = ref("")
	// 上次更新时间
	const lastUpdateTime = ref(0)
	// 用户信息
	const userInfo = ref(clone(defaultUserInfo))
	// 订单信息
	const orderInfo = ref(clone(defaultOrderInfo))

	function setAuth(data: any) {
		auth.value = data
	}
	function setToken(data?: string) {
		if (!data) {
			isLogin.value = false;
			uni.removeStorageSync('token');
		} else {
			isLogin.value = true;
			uni.setStorageSync('token', data);
			loginAfter();
		}
		return isLogin.value;
	}

	// 登录后更新用户信息
	async function loginAfter() {
		await updateUserData();
		await carStore.getList()
		// 提醒绑定手机号
		if (appStore.bindMobile && !userInfo.value.verification?.mobile) {
			setAuth('changeMobile');
		}
	}

	// 更新用户信息
	async function updateUserData() {
		if (!isLogin.value) {
			setToken()
			userInfo.value = clone(defaultUserInfo);
			orderInfo.value = cloneDeep(defaultOrderInfo);
			carStore.clearCar();
			return;
		}
		const nowTime = new Date().getTime();
		if (lastUpdateTime.value + 5000 > nowTime) return;
		Promise.all([getInfo(), getOrder()])
		lastUpdateTime.value = nowTime;
		return userInfo.value;
	}
	// 获取个人信息
	async function getInfo() {
		const data = await getUserInfo();
		userInfo.value = data;
		return Promise.resolve(data);
	}
	// 获取订单信息
	async function getOrder() {
		const data = await getCountOrder()
		orderInfo.value = data;
		return Promise.resolve(data);
	}
	// 重置操作
	function handleReset() {
		setToken();
		userInfo.value = clone(defaultUserInfo);
		orderInfo.value = cloneDeep(defaultOrderInfo);
		carStore.clearCar();
	}
	// 登出
	async function logout() {
		await apiLogout();
		handleReset();
		return !isLogin.value;
	}

	return {
		token,
		auth,
		isLogin,
		setToken,
		setAuth,
		logout
	}
}, {
	persist: true
});

export default useUserStore